package com.intelligent.health.oauth.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.intelligent.health.member.feign.MemberFeignClient;
import entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: torlesse-liang
 * @Date: 2022/03/18/22:09
 * @Description: 自定义UserDetailsService实现类
 */
@Slf4j
@Component(value = "healthUserDetailsService")
public class HealthUserDetailsService implements UserDetailsService {

    @Autowired
    private UserCheckService userCheckService;

    @Autowired
    private MemberFeignClient memberFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("username 账号校验: {}", username);
        // 查询数据库操作
        if (userCheckService.queryUserInfo(username) == null) {
            throw new UsernameNotFoundException("the user is not found");
        } else {
            R result = memberFeignClient.getUserAndAuthInfo(username);

            HashMap hashMap = JSONObject.parseObject(JSON.toJSONString(result.getData()), HashMap.class);
            String password = String.valueOf(hashMap.get("password"));
            ArrayList<String> roleBos = JSONObject.parseObject(JSON.toJSONString(hashMap.get("roleBos")), ArrayList.class);
            Set<String> permissions = JSONObject.parseObject(JSON.toJSONString(hashMap.get("permissions")), Set.class);
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (String roleBo : roleBos) {
                authorities.add(new SimpleGrantedAuthority(roleBo));
            }
            for (String permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }
            // 线上环境应该通过用户名查询数据库获取加密后的密码 userBo.getPassword()
            // 返回自定义的 healthUserDetailsService
            User user = new User(username, password, authorities);
            return user;
        }
    }
}

